const express = require('express');
const router = express.Router();
const os = require('os');
const sited = require('../database/db').sited;
const uuidV4 = require('uuid/v4');
const cheerio = require('cheerio');
const urlDecoder = require('../core/dbSource').urlDecoder;
const request = require('request');
const decodeXml = require('../core/dbSource').decodeXml;
const getTagContent = require('../core/dbSource').getTagContent;
const DOMParser = require('xmldom').DOMParser;

/* GET home page. */
router.get('/', function(req, res, next) {
    sited.find({},{'xml':false},{sort: {updateTime: -1}},function (error, result) {
        // console.log(result);
        let host;
        if (os.platform() === 'darwin' || os.platform() === 'win32') {
            host = 'http://192.168.0.100:3000'
        } else {
            host = 'http://118.24.83.228'
        }
        result.forEach(function (ele, i) {
            let url = host + '/ddcat/api/ddcat.sited.xml?id='+ele._id;
            ele.url = 'sited://data?' + (new Buffer(url).toString('base64'));
            ele.wk_url = '/ddcat/workshop?id=' +ele._id;
            ele.mc_url = '/ddcat/monaco?id=' +ele._id;
        });
        res.render('index', {success:true, data:result});
    });
});

router.get('/upload', function(req, res, next) {
    res.render('upload', { title: '文件上传' });
});

router.get('/workshop', function(req, res, next) {
    if(req.query.id) {
        let id = req.query.id;
        sited.findOne({_id: id},function (error, result) {
            if(error) {
                console.log('error happen');
                res.json({success:false, errMsg:'fail to find'});
                return;
            }
            res.render('workshop', {xml:result.xml, id: id});
        });
    } else {
        res.render('workshop', {xml: ''});
    }
});

router.get('/monaco', function(req, res, next) {
    if(req.query.id) {
        let id = req.query.id;
        sited.findOne({_id: id},function (error, result) {
            if(error) {
                console.log('error happen');
                res.json({success:false, errMsg:'fail to find'});
                return;
            }
            res.render('monaco', {xml:result.xml, id: id});
        });
    } else {
        res.render('monaco', {xml: ''});
    }
});

router.get('/debug', function(req, res, next) {
    res.render('debug');
});

router.get('/update', function(req, resp, next) {
    let data = '';
    let str = '';
    let respXml = '';
    if(req.query.sitedLink) {
        str = decodeURIComponent(req.query.sitedLink);
        console.log(str);
        data = urlDecoder(str);
        console.log("url: "+data);
        let eData = encodeURI(data);
        request(eData, function (err, res, bd) {
            if(!err && res.statusCode === 200) {
                let xml = bd;
                let msg = '';
                if (xml.startsWith('<?xml')) {

                }else if(xml.startsWith('sited::')) {
                    msg ='this is sited encode xml file';
                    console.log(msg);
                    xml = decodeXml(xml);
                } else {
                    xml = null;
                }
                respXml = xml;
                if(xml) {
                    // console.log(xml);
                    const doc = new DOMParser().parseFromString(xml);
                    let title = getTagContent(doc, 'title');
                    let guid = getTagContent(doc, 'guid');
                    let intro = getTagContent(doc, 'intro');
                    let author = getTagContent(doc, 'author');


                    let sited_obj = new sited({
                        title: title,
                        guid: guid,
                        intro: intro,
                        author: author,
                        xml: xml
                    });
                    sited_obj.save(function(err) {
                        if (err) {
                            console.log('保存失败');
                            console.log(err);
                            msg= '保存失败';
                            return;
                        }
                        console.log('保存成功');
                    });
                }

            }else {
                console.log('error happen');
                console.log(err);
                console.log(res.statusCode);
            }
            resp.render('update', {str: str, data: data, xml: respXml});
        })
    }else{
        resp.render('update', {str: str, data: data, xml: respXml});

    }
    console.log("data");
    console.log(data);
});

router.get('/tool', function(req, res, next) {
    let data = '';
    let str = '';
    if(req.query.sited) {
        str = req.query.sited;
        let sited = new Buffer(str);
        data = 'sited://data?' + sited.toString('base64');
    }else if(req.query.base64) {
        str = req.query.base64;
        let sited = new Buffer(str);
        data = sited.toString('base64');
    }else if(req.query.guid) {
        data = uuidV4();
        data = data.replace(new RegExp('-',"gm"), '');
    }else if(req.query.sitedLink) {
        str = decodeURIComponent(req.query.sitedLink);
        console.log(str);
        data = urlDecoder(str);
        console.log(data);
    }
    res.render('tool', {str: str, data: data});
});

router.get('/video', function (req, res, next) {
    let videoUrl = req.query.url;
    //  type='application/x-mpegURL'
    if(!videoUrl){
        videoUrl = 'http://120.52.51.98/clips.vorwaerts-gmbh.de/big_buck_bunny.mp4';
    }
    res.render('video', {url: videoUrl});
});

module.exports = router;
